<template>
  <div class="cateDialog">
    <el-dialog :title="title" :visible.sync="dialogStatus" :before-close="handleClose">
      <el-form label-width="80px">
        <el-form-item label="父级分类">
          <el-select v-model="category.parent">
            <el-option v-for="item in parents" :key="item._id" :label="item.name" :value="item._id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="category.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="setCategory">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
export default {
  props: ["dialogVisible", "title", "dialogId", "parents"],
  data() {
    return {
      category: {
        name: "",
        parent: ""
      }
    };
  },
  methods: {
    handleClose() {
      this.category.name = "";
      this.category.parent = "";
      this.$emit("close", false);
    },
    async setCategory() { //设置分类
      if (this.dialogId) { //修改
        if (!this.category.parent) {
          await this.$http({
            url: "rest/categories/" + this.dialogId, 
            data: { name: this.category.name },
            method: 'PUT',
            headers: {
              Token: this.$store.state.token || ''
            }
          });
        } else {
          await this.$http({
            url: "rest/categories/" + this.dialogId, 
            data: this.category,
            method: 'PUT',
            headers: {
              Token: this.$store.state.token || ''
            }
          });
        }
      } else { //新增
        if (!this.category.parent) {
          await this.$http.post("rest/categories", { name: this.category.name });
        } else {
          await this.$http.post("rest/categories", this.category);
        }
      }
      this.handleClose();
      this.$emit("getCategory");
    },
    async getCateById(id) { //通过id获取分类信息
      const res = await this.$http.get("rest/categories/" + id);
      this.category.name = res.data.name;
      this.category.parent = res.data.parent;
      this.$forceUpdate();
    }
  },
  watch: {
    dialogStatus(val) {
      val && this.dialogId && this.getCateById(this.dialogId);
    }
  },
  computed: {
    dialogStatus() {
      return this.dialogVisible;
    }
  }
};
</script>
<style lang='scss' scoped>
</style>